package com.zhongen.oa.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.s3.model.S3Object;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhongen.admin.api.entity.SysDept;
import com.zhongen.admin.api.entity.SysFile;
import com.zhongen.admin.api.feign.RemoteDeptService;
import com.zhongen.common.core.constant.SecurityConstants;
import com.zhongen.common.core.util.PinyinUtils;
import com.zhongen.common.core.util.R;
import com.zhongen.common.file.core.FileTemplate;
import com.zhongen.common.security.service.PigUser;
import com.zhongen.common.security.util.SecurityUtils;
import com.zhongen.oa.entity.*;
import com.zhongen.oa.entity.vo.ProjectBasicInfoNumVo;
import com.zhongen.oa.entity.vo.ProjectBasicInfoVo;
import com.zhongen.oa.entity.vo.ProjectRequirementVo;
import com.zhongen.oa.mapper.ProjectBasicInfoMapper;
import com.zhongen.oa.mapper.ProjectRequirementMapper;
import com.zhongen.oa.service.ProjectBasicInfoService;
import com.zhongen.oa.service.ProjectFileService;
import com.zhongen.wflow.bean.vo.OrgTreeVo;
import com.zhongen.wflow.service.OrgRepositoryService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import java.io.*;
import java.time.LocalDate;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 项目基本信息表
 *
 * @author Code Generator
 * @date 2024-01-15 12:07:54
 */
@Service
@AllArgsConstructor
public class ProjectBasicInfoServiceImpl extends ServiceImpl<ProjectBasicInfoMapper, ProjectBasicInfoEntity>
		implements ProjectBasicInfoService {

	private final FileTemplate fileTemplate;

	private final RemoteDeptService remoteDeptService;

	private final ProjectFileService projectFileService;

	@Autowired
	private OrgRepositoryService orgRepositoryService;

	@Autowired
	private ProjectRequirementMapper projectRequirementMapper;

	@Override
	public R addProject(ProjectBasicInfoEntity projectBasicInfo) {
		// 项目名称字母大写
		projectBasicInfo.setProjectAbbr(projectBasicInfo.getProjectAbbr().toUpperCase());
		// 校验项目缩写是否存在
		Long exist = baseMapper.selectCount(
				new QueryWrapper<ProjectBasicInfoEntity>().eq("project_abbr", projectBasicInfo.getProjectAbbr()));
		if (exist > 0) {
			return R.failed("项目缩写已存在");
		}
		PigUser user = SecurityUtils.getUser();
		projectBasicInfo.setDeptId(user.getDeptId());
		// 条件参数
		// 项目初始状态
		projectBasicInfo.setProjectStatus("ready");
		// 项目状态.判断立项日期是否小于当前日期,小于则是已立项,立项之后再生成项目编号
		projectBasicInfo.setProjectApprovalStatus("disapproval");
		if (null != projectBasicInfo.getProjectApprovalDate()) {
			// 项目年份根据立项日期自动生成
			projectBasicInfo
				.setProjectYear(LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyyy"));
			if (projectBasicInfo.getProjectApprovalDate().compareTo(LocalDate.now()) <= 0) {
				projectBasicInfo.setProjectApprovalStatus("approval");
				// 查询顺序号
				Long count = baseMapper
					.selectCount(new QueryWrapper<ProjectBasicInfoEntity>().eq("project_approval_status", "approval")
						.eq("DATE_FORMAT (project_approval_date,'%Y-%m')",
								LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyyy-MM")));
				// 生成项目编号
				String area = projectBasicInfo.getArea();
				if (null == area || "".equals(area)) {
					area = projectBasicInfo.getProvince();
				}
				String areaName = "";
				if (null != area && !"".equals(area)) {
					area = projectBasicInfo.getProvince();
					areaName = "-" + PinyinUtils.getPinyinFirstLetter(area);
				}
				String projectType = projectBasicInfo.getProjectType();
				String yearAndMonth = "-" + LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyMM");
				String no = formatNumberToThreeDigits(count + 1);
				String projectCode = projectType + areaName + yearAndMonth + no;
				projectBasicInfo.setProjectNumber(projectCode);
			}
		}
		baseMapper.insert(projectBasicInfo);
		// 插入附件
		ArrayList<ProjectFileEntity> projectFileEntities = new ArrayList<>();
		List<SysFile> fileList = projectBasicInfo.getFileList();
		if (null != fileList && fileList.size() > 0) {
			for (SysFile file : fileList) {
				ProjectFileEntity projectFileEntity = new ProjectFileEntity();
				projectFileEntity.setProjectId(projectBasicInfo.getId());
				projectFileEntity.setFileId(Long.valueOf(file.getId()));
				projectFileEntities.add(projectFileEntity);
			}
			projectFileService.saveBatch(projectFileEntities);
		}
		return R.ok();
	}

	@Override
	public boolean updateById(ProjectBasicInfoEntity projectBasicInfo) {
		// 项目状态.判断立项日期是否小于当前日期,小于则是已立项
		if (null != projectBasicInfo.getProjectApprovalDate()) {
			if (projectBasicInfo.getProjectApprovalDate().compareTo(LocalDate.now()) <= 0) {
				// 如果项目状态是未立项,修改为已立项
				if ("disapproval".equals(projectBasicInfo.getProjectApprovalStatus())) {
					projectBasicInfo.setProjectApprovalStatus("approval");
					// 查询顺序号
					Long count = baseMapper.selectCount(new QueryWrapper<ProjectBasicInfoEntity>()
						.eq("project_approval_status", "approval")
						.eq("DATE_FORMAT (project_approval_date,'%Y-%m')",
								LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyyy-MM")));
					// 生成项目编号
					String area = projectBasicInfo.getArea();
					if (null == area || "".equals(area)) {
						area = projectBasicInfo.getProvince();
					}
					String areaName = "";
					if (null != area && !"".equals(area)) {
						area = projectBasicInfo.getProvince();
						areaName = "-" + PinyinUtils.getPinyinFirstLetter(area);
					}
					String projectType = projectBasicInfo.getProjectType();
					String yearAndMonth = "-"
							+ LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyMM");
					String no = formatNumberToThreeDigits(count + 1);
					String projectCode = projectType + areaName + yearAndMonth + no;
					projectBasicInfo.setProjectNumber(projectCode);
				}
			}
		}
		// 插入附件
		ArrayList<ProjectFileEntity> projectFileEntities = new ArrayList<>();
		List<SysFile> fileList = projectBasicInfo.getFileList();
		baseMapper.updateById(projectBasicInfo);
		if (null != fileList && fileList.size() > 0) {
			projectFileService.remove(new QueryWrapper<ProjectFileEntity>().eq("project_id", projectBasicInfo.getId()));
			for (SysFile file : fileList) {
				ProjectFileEntity projectFileEntity = new ProjectFileEntity();
				projectFileEntity.setProjectId(projectBasicInfo.getId());
				projectFileEntity.setFileId(Long.valueOf(file.getId()));
				projectFileEntities.add(projectFileEntity);
			}
			projectFileService.saveBatch(projectFileEntities);
		}
		return true;
	}

	@Override
	public int removeBatchByIds(List<Long> ids) {
		Wrapper<ProjectBasicInfoEntity> wrapper = new QueryWrapper<ProjectBasicInfoEntity>().in("id", ids)
			.eq("project_approval_status", "disapproval");
		return baseMapper.delete(wrapper);
	}

	@Override
	public IPage<ProjectBasicInfoVo> page(Page page, ProjectBasicInfoEntity projectBasicInfo) {
		PigUser user = SecurityUtils.getUser();
		List<SysDept> deptList = remoteDeptService.listDescendantAndParent(user.getDeptId(), SecurityConstants.FROM_IN);
		HashSet<Long> deptIds = new HashSet<>();
		deptIds.add(user.getDeptId());
		deptList.forEach(sysDept -> {
			deptIds.add(sysDept.getDeptId());
		});
		return baseMapper.queryProjectInfoList(page, projectBasicInfo, deptIds);
	}

	@Override
	public List<ProjectBasicInfoNumVo> getProjectBasicInfoNumApp(ProjectBasicInfoEntity projectBasicInfo) {
		PigUser user = SecurityUtils.getUser();
		List<SysDept> deptList = remoteDeptService.listDescendantAndParent(user.getDeptId(), SecurityConstants.FROM_IN);
		HashSet<Long> deptIds = new HashSet<>();
		deptIds.add(user.getDeptId());
		deptList.forEach(sysDept -> {
			deptIds.add(sysDept.getDeptId());
		});
		List<ProjectBasicInfoNumVo> projectBasicInfoNumApp = baseMapper.getProjectBasicInfoNumApp(projectBasicInfo,
				deptIds);
		List<ProjectBasicInfoNumVo> projectBasicInfoNum = new ArrayList<>();
		Integer doing = 0;
		Integer complete = 0;
		Integer all = 0;
		for (ProjectBasicInfoNumVo projectBasicInfoNumVo : projectBasicInfoNumApp) {
			String projectStatus = projectBasicInfoNumVo.getProjectStatus();
			Integer num = projectBasicInfoNumVo.getProjectNumber();
			if ("doing".equals(projectStatus)) {
				doing = num;
			}
			if ("complete".equals(projectStatus)) {
				complete = num;
			}
			all += num;
		}
		projectBasicInfoNum.add(new ProjectBasicInfoNumVo("进行中", doing));
		projectBasicInfoNum.add(new ProjectBasicInfoNumVo("已完成", complete));
		projectBasicInfoNum.add(new ProjectBasicInfoNumVo("全部", all));
		return projectBasicInfoNum;
	}

	@Override
	public ProjectBasicInfoVo getProjectInfoById(Long id) {
		return baseMapper.getProjectInfoById(id);
	}

	@Override
	public int updateProjectStatusById(String id, String status) {
		UpdateWrapper<ProjectBasicInfoEntity> updateWrapper = new UpdateWrapper<>();
		// 如果状态是approval，立项日期不允许为空,更新立项日期
		if ("approval".equals(status)) {
			updateWrapper.set("project_approval_date", LocalDate.now());
		}
		// 如果状态是doing,更新项目实际开始日期
		if ("doing".equals(status)) {
			// 如果原来就有开始日期,可能是由挂起状态变为进行状态,不更新日期
			if (null == baseMapper.getProjectInfoById(Long.valueOf(id)).getRealStartDate()) {
				updateWrapper.set("real_start_date", LocalDate.now());
			}
		}
		// 如果状态是complete,更新项目实际完成日期
		if ("complete".equals(status)) {
			// 如果原来就有完成日期,可能是由进行状态变为完成状态,不更新日期
			updateWrapper.set("real_end_date", LocalDate.now());
		}
		updateWrapper.set("project_status", status).eq("id", id);
		return baseMapper.update(null, updateWrapper);
	}

	@Override
	public void projectStatusUpdateTask() {
		// 查询符合条件的列表
		List<ProjectBasicInfoEntity> list = baseMapper.selectList(new QueryWrapper<ProjectBasicInfoEntity>()
			.eq("project_approval_status", "disapproval")
			.eq("DATE_FORMAT (project_approval_date,'%Y-%m')", LocalDateTimeUtil.format(LocalDate.now(), "yyyy-MM")));
		// 遍历列表,组转项目编号,更新项目状态
		if (!list.isEmpty()) {
			UpdateWrapper<ProjectBasicInfoEntity> updateWrapper = new UpdateWrapper<>();
			for (ProjectBasicInfoEntity projectBasicInfo : list) {
				// 更新项目状态
				projectBasicInfo.setProjectApprovalStatus("approval");
				// 查询顺序号
				Long count = baseMapper
					.selectCount(new QueryWrapper<ProjectBasicInfoEntity>().eq("project_approval_status", "approval")
						.eq("DATE_FORMAT (project_approval_date,'%Y-%m')",
								LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyyy-MM")));
				// 生成项目编号
				String area = projectBasicInfo.getArea();
				if (null == area || "".equals(area)) {
					area = projectBasicInfo.getProvince();
				}
				String areaName = "";
				if (null != area && !"".equals(area)) {
					area = projectBasicInfo.getProvince();
					areaName = "-" + PinyinUtils.getPinyinFirstLetter(area);
				}
				String projectType = projectBasicInfo.getProjectType();
				String yearAndMonth = "-" + LocalDateTimeUtil.format(projectBasicInfo.getProjectApprovalDate(), "yyMM");
				String no = formatNumberToThreeDigits(count + 1);
				String projectCode = projectType + areaName + yearAndMonth + no;
				projectBasicInfo.setProjectNumber(projectCode);
				updateWrapper.set("project_approval_status", "approval").set("project_number", projectCode);
				updateWrapper.eq("id", projectBasicInfo.getId());
				baseMapper.update(updateWrapper);
			}
		}
	}

	@Override
	public void queryProjectInfoAll(HttpServletResponse response, ProjectBasicInfoEntity projectBasicInfo) {
		PigUser user = SecurityUtils.getUser();
		List<SysDept> deptList = remoteDeptService.listDescendantAndParent(user.getDeptId(), SecurityConstants.FROM_IN);
		HashSet<Long> deptIds = new HashSet<>();
		deptIds.add(user.getDeptId());
		deptList.forEach(sysDept -> {
			deptIds.add(sysDept.getDeptId());
		});
		List<ProjectBasicInfoVo> projectBasicInfoVos = baseMapper.queryProjectInfoAll(projectBasicInfo, deptIds);
		excel(response, projectBasicInfoVos);
	}

	@Override
	public ProjectBasicInfoNum getNumByIdApp(Long id) {
		ProjectBasicInfoVo projectInfoById = baseMapper.getProjectInfoById(id);
		Long deptId = projectInfoById.getDeptId();
		List<SysDept> deptList = remoteDeptService.listDescendantAndParent(deptId, SecurityConstants.FROM_IN);
		ProjectBasicInfoNum projectBasicInfoNum = new ProjectBasicInfoNum();
		projectBasicInfoNum.setPeopleNum(0);
		// 获取部门下所有人数
		if (deptId != null) {
			Collection<String> deptIds = new Stack<>();
			for (SysDept sysDept : deptList) {
				deptIds.add(sysDept.getDeptId().toString());
			}
			Set<String> usersByDepts = orgRepositoryService.getUsersByDepts(deptIds);
			projectBasicInfoNum.setPeopleNum(usersByDepts.size());
		}

		// 获取项目下所有需求

		int demandNum = 0;
		int demandCompletedNum = 0;
		int demandIncompleteNum = 0;
		List<Long> ids = new ArrayList<>();
		List<ProjectRequirementVo> requirementVoList = projectRequirementMapper
			.getListByProjectId(projectInfoById.getId());
		for (ProjectRequirementVo projectRequirementVo : requirementVoList) {
			demandNum++;
			// 判断是否完成
			if ("closed".equals(projectRequirementVo.getRequirementStatus())) {
				demandCompletedNum++;
			}
			else {
				demandIncompleteNum++;
			}
			ids.add(projectRequirementVo.getId());
		}
		projectBasicInfoNum.setDemandNum(demandNum);
		projectBasicInfoNum.setDemandCompletedNum(demandCompletedNum);
		projectBasicInfoNum.setDemandIncompleteNum(demandIncompleteNum);

		List<ProjectMainTaskEntity> taskList = baseMapper.getTaskAll(id, ids);

		List<Long> mainTaskId = new ArrayList<>();
		List<Long> subTaskId = new ArrayList<>();

		// 获取项目下所有任务
		int estimatedWorkingHours = 0;
		int realityWorkingHours = 0;
		int taskWaitNum = 0;
		int taskDoingNum = 0;
		int taskClosedNum = 0;

		for (ProjectMainTaskEntity projectMainTaskEntity : taskList) {
			Long taskId = projectMainTaskEntity.getId();
			// 获取id 为bug数做准备
			if ("主线".equals(projectMainTaskEntity.getTaskName())) {
				mainTaskId.add(taskId);
			}
			else {
				subTaskId.add(taskId);
			}
			// 判断是否完成
			String taskStatus = projectMainTaskEntity.getTaskStatus();
			if ("wait".equals(taskStatus)) {
				taskWaitNum++;
			}
			else if ("doing".equals(taskStatus)) {
				taskDoingNum++;
			}
			else if ("closed".equals(taskStatus)) {
				taskClosedNum++;
			}
			if(projectMainTaskEntity.getEstimatedWorkingHours()!=null){
				estimatedWorkingHours += projectMainTaskEntity.getEstimatedWorkingHours();
			}
			if(projectMainTaskEntity.getRealityWorkingHours()!=null){
				realityWorkingHours += projectMainTaskEntity.getRealityWorkingHours();
			}
		}
		projectBasicInfoNum.setEstimatedWorkingHours(estimatedWorkingHours);
		projectBasicInfoNum.setRealityWorkingHours(realityWorkingHours);
		projectBasicInfoNum.setTaskWaitNum(taskWaitNum);
		projectBasicInfoNum.setTaskDoingNum(taskDoingNum);
		projectBasicInfoNum.setTaskClosedNum(taskClosedNum);

		int bugNum = 0;
		int bugCompletedNum = 0;
		int bugIncompleteNum = 0;
		if (mainTaskId.size() > 0 || subTaskId.size() > 0) {
			List<ProjectTaskBugEntity> bugList = baseMapper.getBugList(mainTaskId, subTaskId);
			for (ProjectTaskBugEntity projectTaskBugEntity : bugList) {
				bugNum++;
				// 判断是否完成
				if ("closed".equals(projectTaskBugEntity.getBugStatus())) {
					bugCompletedNum++;
				}
				else {
					bugIncompleteNum++;
				}
			}
		}
		projectBasicInfoNum.setBugNum(bugNum);
		projectBasicInfoNum.setBugCompletedNum(bugCompletedNum);
		projectBasicInfoNum.setBugIncompleteNum(bugIncompleteNum);
		return projectBasicInfoNum;
	}

	private void excel(HttpServletResponse response, List<ProjectBasicInfoVo> projectBasicInfoVos) {
		try {
			SXSSFWorkbook workbook = new SXSSFWorkbook();

			// 创建工作表，指定工作表名称
			SXSSFSheet sheet = workbook.createSheet("项目信息表");

			SXSSFRow row = sheet.createRow(0);
			String[] names = { "项目编号", "项目名称", "省份", "地区", "产品线", "项目内容", "项目状态", "项目进度", "项目负责人", "技术负责人", "营销负责人",
					"商务负责人", "甲方单位", "过手单位", "合同属性", "合同编号", "合同流转时间", "合同名称" };

			for (int i = 0; i < names.length; i++) {
				SXSSFCell cell = row.createCell(i);
				cell.setCellValue(names[i]);
			}

			int count = 1;

			List<Long> projectIds = new ArrayList<>();
			List<Long> contractIds = new ArrayList<>();

			for (ProjectBasicInfoVo projectBasicInfoVo : projectBasicInfoVos) {
				projectIds.add(projectBasicInfoVo.getId());
				SXSSFRow rowNum = sheet.createRow(count);
				// 项目编号
				rowNum.createCell(0).setCellValue(projectBasicInfoVo.getProjectNumber());
				// 项目名称
				rowNum.createCell(1).setCellValue(projectBasicInfoVo.getProjectName());
				// 省份
				rowNum.createCell(2).setCellValue(projectBasicInfoVo.getProvince());
				// 地区
				rowNum.createCell(3).setCellValue(projectBasicInfoVo.getArea());
				// 产品线
				rowNum.createCell(4).setCellValue("产品线");
				// 项目内容
				rowNum.createCell(5).setCellValue(projectBasicInfoVo.getProjectContent());
				// 项目状态
				rowNum.createCell(6).setCellValue(projectBasicInfoVo.getProjectStatus());
				// 项目进度
				rowNum.createCell(7).setCellValue(projectBasicInfoVo.getProjectSchedule());
				// 项目负责人
				rowNum.createCell(8).setCellValue(projectBasicInfoVo.getProjectMyHead());
				// 技术负责人
				rowNum.createCell(9).setCellValue(projectBasicInfoVo.getProjectMyTechnologyHead());
				// 营销负责人
				rowNum.createCell(10).setCellValue(projectBasicInfoVo.getProjectMyMarketHead());
				// 商务负责人
				rowNum.createCell(11).setCellValue(projectBasicInfoVo.getProjectMyBusinessHead());
				// 甲方单位
				rowNum.createCell(12).setCellValue(projectBasicInfoVo.getPartAUnit());
				// 过手单位
				rowNum.createCell(13).setCellValue(projectBasicInfoVo.getPassingUnit());
				if (projectBasicInfoVo.getProjectContractList() != null
						&& !projectBasicInfoVo.getProjectContractList().isEmpty()) {
					List<ProjectContractEntity> projectContractList = projectBasicInfoVo.getProjectContractList();
					int startCount = count;
					for (int i = 0; i < projectContractList.size(); i++) {
						ProjectContractEntity projectContractEntity = projectContractList.get(i);
						contractIds.add(projectContractEntity.getId());
						if (i != 0) {
							rowNum = sheet.createRow(count);
						}
						// 合同属性
						rowNum.createCell(14).setCellValue("合同属性");
						// 合同编号
						rowNum.createCell(15).setCellValue(projectContractEntity.getContractNumber());
						// 合同流转时间
						rowNum.createCell(16).setCellValue(projectContractEntity.getCirculationDate());
						// 合同名称
						rowNum.createCell(17).setCellValue(projectContractEntity.getContractName());
						count++;
					}
					if (startCount != (count - 1)) {
						for (int i = 0; i < 14; i++) {
							sheet.addMergedRegion(new CellRangeAddress(startCount, count - 1, i, i));
						}
					}
				}
				else {
					count++;
				}
			}
			ByteArrayOutputStream xlsxOutputStream = new ByteArrayOutputStream();
			workbook.write(xlsxOutputStream);
			workbook.close();

			// 3. 使用Java的ZipOutputStream类将xlsx文件和其他文件组装成一个zip文件
			ByteArrayOutputStream zipOutputStream = new ByteArrayOutputStream();
			ZipOutputStream zos = new ZipOutputStream(zipOutputStream);
			zos.putNextEntry(new ZipEntry("项目信息表.xlsx"));
			zos.write(xlsxOutputStream.toByteArray());
			zos.closeEntry();

			List<JSONObject> fileList = baseMapper.getFileList(projectIds, contractIds);

			Map<String, Integer> fileNameMap = new HashMap<>();
			for (JSONObject file : fileList) {

				String fileName = file.getString("file_name");
				String bucketName = file.getString("bucket_name");
				String original = file.getString("original");
				String contractNumber = file.getString("contract_number");
				String projectNumber = file.getString("project_number");
				// zip里面的文件名
				String name = "";
				if (contractNumber == null || "".equals(contractNumber)) {
					name = projectNumber + "/" + original;
				}
				else {
					name = projectNumber + "/" + contractNumber + "/" + original;
				}
				// 判断文件名是否重复
				if (fileNameMap.containsKey(name)) {
					Integer integer = fileNameMap.get(name);
					String[] split = name.split("\\.");
					zos.putNextEntry(new ZipEntry(split[0] + "(" + integer + ")." + split[1]));
					fileNameMap.put(name, integer + 1);
				}
				else {
					zos.putNextEntry(new ZipEntry(name));
					fileNameMap.put(name, 1);
				}

				S3Object s3Object = fileTemplate.getObject(bucketName, fileName);
				InputStream inputStream = s3Object.getObjectContent();

				byte[] buffer = new byte[1024];
				int bytesRead;
				while ((bytesRead = inputStream.read(buffer)) > 0) {
					zos.write(buffer, 0, bytesRead);
				}

				inputStream.close();
				zos.closeEntry();
			}
			zos.close();
			IoUtil.close(zos);

			// zip压缩包数据
			byte[] data = zipOutputStream.toByteArray();

			response.reset();
			response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=项目信息.zip"));
			response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
			response.setContentType("application/octet-stream; charset=UTF-8");
			IoUtil.write(response.getOutputStream(), false, data);
		}
		catch (Exception e) {
			String message = e.getMessage();
			System.err.println(message);
		}

	}

	// /**
	// * 写入到 response 表头
	// * @param excelName
	// * @param workbook
	// * @param response
	// * @throws IOException
	// */
	// public void responseImport(String excelName, SXSSFWorkbook workbook,
	// HttpServletResponse response) throws IOException {
	// StringBuffer sb = new StringBuffer();
	// sb.append(excelName);
	// sb.append(".xlsx");
	//
	// ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	// workbook.write(outputStream);
	// IOUtils.closeQuietly(workbook);
	// byte[] bytes = outputStream.toByteArray();
	//
	// // 响应客户端浏览器区分数据
	// response.reset(); // 清空首部
	// response.setContentType("application/vnd.ms-excel; charset=UTF-8");
	// // 没有缓存
	// response.setHeader("Cache-Control", "No-cache");
	// // 没有缓存
	// response.setHeader("Pragma", "No-cache");
	// // 设置文件名
	// response.setHeader("Content-Disposition", "attachment; filename=" +
	// java.net.URLEncoder.encode(sb.toString(), "UTF-8"));
	// response.addHeader("Content-Length", String.valueOf(bytes.length));
	//
	// IOUtils.write(bytes, response.getOutputStream());
	//
	// workbook.close();
	// }

	private String formatNumberToThreeDigits(long number) {
		String numberString = String.valueOf(number);
		if (numberString.length() < 3) {
			numberString = String.format("%02d", number);
		}
		return numberString;
	}

}
